﻿using Newtonsoft.Json;
using QskjGetUrlDownUpAlarm.Dto;
using QskjLibrary;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace QskjGetUrlDownUpAlarm.Service
{
    public static class VideoImageUrl
    {
        /// <summary>
        /// 视图库视频文件查询
        /// </summary>
        /// <returns></returns>
        public static async Task<string> GetFileDataUrl(string key, string dts, string dte, string begintime)
        {
            var client = new HttpClient();
            var request = new HttpRequestMessage(HttpMethod.Get, $@"http://192.168.3.223:8000/VIID/VideoSlices?VideoID={key}&BeginTime={begintime}");
            var response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string res = await response.Content.ReadAsStringAsync();
            return res;
        }
        ///// <summary>
        ///// 视图库图片文件查询
        ///// </summary>
        ///// <param name="key">Id</param>
        ///// <returns></returns>
        //public static async Task<string> GetImageFileDataUrl(string key, string dts, string dte)
        //{
        //    var client = new HttpClient();
        //    var request = new HttpRequestMessage(HttpMethod.Get, $@"http://192.168.3.223:8000/VIID/Images?ImageID={key}&EntryTime>{dts}&EntryTime<{dte}&Fields=StoragePath");
        //    var response = await client.SendAsync(request);
        //    response.EnsureSuccessStatusCode();
        //    string res = await response.Content.ReadAsStringAsync();
        //    return res;
        //}
        public static void GetInfox(int day)
        {
            try
            {

                string dtStr = DateTime.Now.AddDays(day).ToString("yyyyMMdd");
                string sql = $@"select * from qskjrecord.B_FileResourceInfo{dtStr} where urladdress is null order by id limit 2;";
                DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sql);
                foreach (DataRow dr in dt.Rows)
                {
                    string url = null, ip = "_";
                    try
                    {
                        string bt = dr["begintime"] == DBNull.Value ? null : dr["begintime"].ToString();
                        // ThreadPoll启动多线程
                        ThreadPool.QueueUserWorkItem(p => GetUrlThread(dr["filekey"].ToString(), dr["filetype"].ToString(), dr["id"].ToString(), dtStr, bt));
                        Thread.Sleep(500);
                        //
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "遍历数据异常：" + e.Message + "_" + url);
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "查询数据异常：" + ex.Message);
                return;
            }
        }
        public static void GetUrlThread(string filekey, string filetype, string id, string dtStr, string begintime)
        {
            string url = null, ip = "_";
            try
            {
                url = GetUrl(filekey, filetype, begintime);
                if (string.IsNullOrWhiteSpace(url)) { url = "_"; }
                else { string[] ips = url.Split(':'); ip = ips[1].Replace("/", ""); }
                string sqlUpdate = $@"update qskjrecord.B_FileResourceInfo{dtStr} set urladdress='{url}',ipaddress='{ip}',updatetime=now() where id ={id} ";
                MySqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdate);
            }
            catch (Exception e)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "遍历数据异常：" + e.Message + "_" + url);
            }
        }
        public static void GetInfo(int day)
        {
            try
            {

                string dtStr = DateTime.Now.AddDays(day).ToString("yyyyMMdd");
                string sql = $@"select * from qskjrecord.B_FileResourceInfo{dtStr} where urladdress is null order by id limit 1000;";
                DataTable dt = MySqlHelper.GetDataTable(CommandType.Text, sql);
                foreach (DataRow dr in dt.Rows)
                {
                    string url = null, ip = "_";
                    try
                    {
                        string bt = dr["begintime"] == DBNull.Value ? null : dr["begintime"].ToString();
                        url = GetUrl(dr["filekey"].ToString(), dr["filetype"].ToString(), bt);
                        if (string.IsNullOrWhiteSpace(url)) { url = "_"; }
                        else { string[] ips = url.Split(':'); ip = ips[1].Replace("/", ""); }
                        string sqlUpdate = $@"update qskjrecord.B_FileResourceInfo{dtStr} set urladdress='{url}',ipaddress='{ip}',updatetime=now() where id ={dr["id"]} ";
                        MySqlHelper.ExecuteNonQuery(CommandType.Text, sqlUpdate);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "遍历数据异常：" + e.Message + "_" + url);
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "查询数据异常：" + ex.Message);
                return;
            }
        }
        public static string GetUrl(string key, string ft, string begintime)
        {
            string url = string.Empty;
            try
            {
                string videoUrl = string.Empty, imageUrl = string.Empty;
                string dte = DateTime.Now.ToString("yyyyMMddHHmmss"), dts = DateTime.Now.AddMinutes(-30).ToString("yyyyMMddHHmmss");
                if (ft == "mp4")
                {
                    try
                    {
                        DataVideoUrl videoData = new DataVideoUrl();
                        videoUrl = GetFileDataUrl(key, dts, dte, begintime).Result;
                        videoData = JsonConvert.DeserializeObject<DataVideoUrl>(videoUrl);
                        if (!string.IsNullOrEmpty(videoData?.VideoSliceListObject?.VideoSlice[0]?.VideoSliceInfo?.StoragePath))
                        {
                            url = videoData?.VideoSliceListObject?.VideoSlice[0]?.VideoSliceInfo?.StoragePath;//视图库视频地址信息
                        }
                        return url;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "视频地址查询异常：" + e.Message);
                        return url;
                    }
                }
                else
                {
                    try
                    {
                        //DataImageUrl imageData = new DataImageUrl();
                        //imageUrl = GetImageFileDataUrl(key, dts, dte).Result;
                        //imageData = JsonConvert.DeserializeObject<DataImageUrl>(imageUrl);
                        //if (!string.IsNullOrEmpty(imageData?.ImageListObject?.Image[0]?.ImageInfo?.StoragePath))
                        //{
                        //    url = imageData?.ImageListObject?.Image[0]?.ImageInfo?.StoragePath;
                        //}
                        return url;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "图片地址查询异常：" + e.Message);
                        return url;
                    }

                }
            }
            catch (Exception e)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "证据地址查询异常：" + e.Message);
                return url;
            }
        }
    }
}
